package rabbitmq.work;

import com.rabbitmq.client.*;
import rabbitmq.constants.Constants;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = factory.newConnection();
        // 2.创建Channel
        Channel channel = connection.createChannel();
        // 3.声明队列（如果队列已经存在可省略，如果不存在省略此声明的话会报错，建议不要省略）
        channel.queueDeclare(Constants.WORK_QUEUE,true,false,false,null);
        // 4.消费消息
        Consumer consumer = new DefaultConsumer(channel){
            // 从队列中收到消息，就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("Consumer1接收到消息：" + new String(body));
            }
        };
        channel.basicConsume(Constants.WORK_QUEUE,true,consumer);

//        // 5.释放资源(先启动消费者不进行资源释放，否则消费者无法长时间运行)
//        channel.close();
//        connection.close();
    }
}
